#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/9/2 14:37
# @Author : wn 
# @File: positionSearch.py
# @SoftWare: PyCharm
# @Site:
# @Table:
#｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡

from django.shortcuts import render,redirect,HttpResponse
from django.http import JsonResponse
from django.views import View
from Manager.utils.mypage import my_page
from Manager.models import *
from operator import itemgetter
from Manager.utils.model_choices import *
import json
from Manager.utils.pageSearch import *

class PositionSearch(View):
    def get(self, request):
        # 当前在第几页
        off = request.GET.get('offset', None)
        # 一页几条
        lim = request.GET.get('limit', None)
        if lim is None:
            html = "positionSearch.html"
            return render(request, html, {'url': '/strategy/position_list'})
        else:
            result_list = []
            # 报单查询
            import datetime
            nowtime = datetime.datetime.now().strftime('%Y%m%d')
            po_list = list(Ruleposition.objects.filter(tradingday=nowtime))
            for item in po_list:
                result_dict = {}
                result_dict['Tradingday'] = item.tradingday
                result_dict['InstrumentID'] = item.instrumentid
                result_dict['CombiNo'] = item.combino
                result_dict['ExchangeID'] = item.exchangeid
                result_dict['PosiDirection'] = PosiDirectionChoices.get(item.posidirection,None)
                result_dict['HedgeFlag'] = HedgeFlagChoices.get(item.hedgeflag,None)
                result_dict['Position'] = item.position
                result_dict['YdPosition'] = item.ydposition
                result_dict['FrozenPositon'] = item.frozenposition
                result_list.append(result_dict)
            # 排序
            for item in result_list:
                if (item.get('tradingday') is None):
                    item['tradingday'] = '-1'
            result_list_sorted = sorted(result_list, key=itemgetter('tradingday'), reverse=True)
            result = my_page(result_list_sorted, lim, off)
            return JsonResponse(result, safe=False)

    def post(self, request):
        if request.POST.get('positionSearch_select', None):
            data = json.loads(request.POST.get('data'))
            Tradingday = data.get('Tradingday', None)
            PosiDirection = data.get('PosiDirection', None)
            CombiNo = data.get('CombiNo', None)
            InstrumentID = data.get('InstrumentID', None)
            jsonRes = search_positionsearch(Tradingday=Tradingday, CombiNo=CombiNo, InstrumentID=InstrumentID, PosiDirection = PosiDirection)
            return jsonRes

